// miniprogram/pages/study/study.js
const util = require('../../utils/util.js');
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    score: 0,
    percent: 0,
    btnText: '下一题',
    rightNum: 0,
    status: 0,
    idx: 0,
    length: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading({
      title: '加载中',
    })
    console.log(options);
    let id = options.id || '';
    let uuid = options.uuid || '';
    this.setData({
      uuid
    },()=>{
      
    })
    this.onQuery();
    this.onGetOpenid();
  },
  
  onQuery: function(id){
    let that = this;
    const db = wx.cloud.database();

    db.collection('questions')
    .aggregate()
    .match({
      category: app.globalData.category._id
    })
    .sample({
      size: 10
    })
    .end()
    .then(res => {
      console.log('[数据库] [查询记录] 成功: ', res)
      let questions = res.list;
      questions.forEach((ques,idx)=>{
        ques.index = idx;
        ques.selected = false;

        let options = ques.options;
        options.forEach(option => {
          option.selected = false;
        });
        ques.options = options;
      })
      let question = questions[0];

      let nums = parseInt(question.rightnums) +  parseInt(question.wrongnums);
      if(nums == 0){
        nums = 1;
      }
      console.log(question.rightnums);
      console.log(nums);
      console.log(question.rightnums/nums);
      let rate = (question.rightnums/nums)*100;

      that.setData({
        rate: rate.toFixed(2) + '%',
        question,
        questions,
        length: questions.length
      },()=>{
        wx.hideLoading()
        console.log(question);
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.onGetTime();
    this.onGetUUID();
    this.queryProfile();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  generate: function(){
    return util.formatTime(new Date());
  },
  addNote: function(){
    let that = this;
    let idx = this.data.idx;
    let questions = this.data.questions;
    let question = questions[idx];
    let qid = question['_id'];
    const db = wx.cloud.database()
    db.collection('notes').add({
      data: {
        uuid: this.data.uuid,
        qid: qid,
        question: question
      },
      success: res => {
        console.log('[数据库] [新增记录] 成功，记录 _id: ', res._id)
        // 在返回结果中会包含新创建的记录的 _id
        // wx.showToast({
        //   title: '新增记录成功',
        // })
        
        
      },
      fail: err => {
        wx.showToast({
          icon: 'none',
          title: '新增记录失败'
        })
        console.error('[数据库] [新增记录] 失败：', err)
      }
    })
  },
  select: function(e){
    let status = this.data.status;
    if(status == 2){
      wx.showToast({
        icon: 'none',
        title: '您已提交'
      })
      return;
    }
    console.log(e.currentTarget.dataset);
    let code = e.currentTarget.dataset.code;
    let option = JSON.parse(e.currentTarget.dataset.value);
    console.log('单选选中事件');
    console.log(option);
    let questions = this.data.questions;
    let idx = this.data.idx;
    let question = this.data.questions[idx];
    let options = question.options;
    let arr = [];
    let typecode = question.typecode;
    switch(typecode+''){
      case '01':
        options.forEach(element => {
          element.selected = false;
          if(code == element.code){
            element.selected = true;
          }
          arr.push(element);
        });
        break;
        case '02':
          options.forEach(element => {
            
            if(code == element.code){
              element.selected = !element.selected;
            }
            arr.push(element);
          });
          break;
        case '03':
          options.forEach(element => {
            element.selected = false;
            if(code == element.code){
              element.selected = true;
            }
            arr.push(element);
          });
          break;        
    }
    let codeArr = [];
    options.forEach(option=>{
      if(option.selected){
        codeArr.push(option.code)
      }
    })

    question.options = arr;
    questions[idx] = question;
    this.setData({
      code: codeArr.join(','),
      status: 1,
      question,
      options: arr,
      questions
    })
  },
  changeStatus: function(){
    let question = this.data.question;
    let options = this.data.options;
    let right = 0;

    let selected = false;
    options.forEach(option => {
      if(option.selected){
        selected = true;
      }
    })
    
    if(!selected){
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: '请先选择您的答案',
        confirmText: '我知道了',
        success (res) {
          if (res.confirm) {
            console.log('用户点击确定')
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      return;
    }

    let codeArr = [];
    options.forEach(option=>{
      if(option.selected){
        codeArr.push(option.code)
      }
    })

    console.log(codeArr.join(''));
    console.log(question.answer);
    if(codeArr.join('') == question.answer){
      right = 1;
    }
    if(right == 1){
      this.setData({
        rightNum: this.data.rightNum+1
      })
    }else{
      this.addNote();
    }
    this.setData({
      status: 2
    },()=>{
      
    })
  },
  addLog: function(){

    let time = util.getTime(new Date());

    const db = wx.cloud.database()
    db.collection('logs').add({
      data: {
        page: 'pages/exam/exam',
        data: this.data,
        time
      }
      })
      .then(res=>{
        console.log('[数据库] [新增记录] 成功，记录 _id: ', res._id)
        // 在返回结果中会包含新创建的记录的 _id  

      })
      .catch(err=>{

      })
  },

  
  generate: function(){
    return util.formatTime(new Date());
  },
  doNext: function(){
    console.log('doNext')
    let idx = this.data.idx+1;
    let questions = this.data.questions;
    let length = this.data.length;
    let percent = (idx/length)*100;
    if(length-idx == 1){
      this.setData({
        btnText: '完成'
      })
      wx.showToast({
        icon: 'none',
        title: '已经是最后一题了'
      })
    }
    if(idx == length){
      wx.showLoading({
        title: '处理中',
        mask: true
      })
      // 最后一题更新记录
      this.addHistory();
      return;
    }

    let question = questions[idx];
    let nums = parseInt(question.rightnums) +  parseInt(question.wrongnums);
    if(nums == 0){
      nums = 1;
    }
    console.log(question.rightnums);
    console.log(nums);
    console.log(question.rightnums/nums);
    let rate = (question.rightnums/nums)*100;
    wx.showLoading({
      title: '跳转中',
      mask: true
    })
    setTimeout(() => {
      this.setData({
        rate: rate.toFixed(2) + '%',
        percent,
        idx,
        status: 0,
        question
      },()=>{
        wx.hideLoading()
      })
    }, 2000);


  },
  addHistory: function(){
    let time = this.data.time;
    const db = wx.cloud.database()

    let score = parseInt(this.data.rightNum);
    db.collection('records').add({
      data: {
        _id: this.data.uuid,
        questions: this.data.questions,
        name: this.data.name,
        dept: this.data.dept,
        score,
        today: this.data.today,
        createTime: time
      }
      })
      .then(res=>{
        console.log('[数据库] [新增记录] 成功，记录 _id: ', res._id)
        // 在返回结果中会包含新创建的记录的 _id  
        this.updateInfo(score);
        
      })
      .catch(err=>{

      })
  },
  updateInfo: function(num){

    let openid = app.globalData.openid;

    const db = wx.cloud.database()
    const _ = db.command
    db.collection('points').doc(openid).update({
      data: {
        // 表示指示数据库将字段自增 10
        num: _.inc(num)
      }
    })
    .then(res=>{
      this.goResult();
    })
  },
  goResult: function(){
    this.addLog();
    let rightNum = parseInt(this.data.rightNum);
      wx.hideLoading()
      let url = '/pages/reviewresult/reviewresult?uuid='+this.data.uuid+'&length='+this.data.length+'&rightNum='+rightNum;
      wx.redirectTo({
        url: url
      })
  },
  queryProfile: function(){

    let openid = app.globalData.openid;

    let that = this;
    const db = wx.cloud.database()
    db.collection('profiles')
    .doc(openid)
    .get()
    .then((res)=>{
      console.log('[数据库] [查询记录] 成功: ', res);
      this.setData({
        name: res.data.name,
        dept: res.data.dept
      })
    })
    .catch((err)=>{
      console.log(err)
      console.error('[数据库] [查询记录] 失败：', err)
      wx.showToast({
        icon: 'none',
        title: '查询记录失败'
      })
    })
  },
  onGetOpenid: function() {
    let that = this;
    // 调用云函数
    wx.cloud.callFunction({
      name: 'login',
      data: {},
      success: res => {
        console.log('[云函数] [login]: ', res)
        app.globalData.openid = res.result.openid
        that.setData({
          openid: res.result.openid
        })
        // wx.navigateTo({
        //   url: '../userConsole/userConsole',
        // })
      },
      fail: err => {
        console.error('[云函数] [login] 调用失败', err)
        wx.navigateTo({
          url: '../deployFunctions/deployFunctions',
        })
      }
    })
  },
  onGetTime: function(){
    let time = util.formatTime(new Date());
    wx.cloud.callFunction({
      // 云函数名称
      name: 'getTime',
      // 传给云函数的参数
      data: {
      },
    })
    .then(res => {
      console.log('[云函数] [getTime]: ', res)
      this.setData({
        today: res.result.today,
        time: res.result.time
      })
    })
    .catch((err)=>{
      console.error('[云函数] [getTime] 调用失败', err)
      wx.navigateTo({
        url: '../deployFunctions/deployFunctions',
      })
    })
    
  },

  onGetUUID: function() {
    // 调用云函数
    let that = this;
    wx.cloud.callFunction({
      name: 'getUUID',
      data: {

      }
    })
    .then(res => {
      console.log('[云函数] [getUUID]: ', res)
      this.setData({
        uuid: res.result.uuid
      },()=>{
        console.log(this.data.uuid);
      })
      
    }).catch(err => {
      console.error('[云函数] [getUUID] 调用失败', err)
      wx.navigateTo({
        url: '../deployFunctions/deployFunctions',
      })
    })
  }
})